package cn.ac.van.imeigen.controller;

import cn.ac.van.imeigen.model.FailResp;
import cn.ac.van.imeigen.model.GenImg;
import cn.ac.van.imeigen.model.ImgResp;
import cn.ac.van.imeigen.model.RespModel;
import cn.ac.van.imeigen.utils.FileLoadUtil;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;

@Controller
public class ImgController {
  @RequestMapping({"/", "/index"})
  public String index() {
    return "index";
  }

  @PostMapping("/api/getImg")
  @ResponseBody
  public RespModel getImg(@RequestBody ImgReq imgReq) {
    //SF Mono Medium、Avenir LT Std 65 Medium
    Font mono, avenir;
    //生成的图片集合
    ArrayList<GenImg> imgList = new ArrayList<>();
    try {
      //初始化字体配置
      mono = Font.createFont(Font.TRUETYPE_FONT, FileLoadUtil.loadFont("monoregular.ttf"));
      avenir = Font.createFont(Font.TRUETYPE_FONT, FileLoadUtil.loadFont("avenir.ttf"));
      mono = mono.deriveFont(Font.PLAIN, 35);
      avenir = avenir.deriveFont(Font.PLAIN, 35);

      for (int i = 0; i < imgReq.getIMEIs().size(); i++) {
        //处理元数据：IMEI列表
        String originIMEI = imgReq.getIMEIs().get(i);
        originIMEI = originIMEI.trim();
        originIMEI = originIMEI.replaceAll(" ", "");
        if (originIMEI.length() != 15) {
          if (originIMEI.length() == 17) {
            System.out.println("无效的iPhone IMEI：" + originIMEI);
            imgList.add(new GenImg(originIMEI, "-1"));
          } else {
            System.out.println("无效的IMEI：" + originIMEI);
            imgList.add(new GenImg(originIMEI, "-2"));
          }
        } else {
          //处理IMEI至iPhone显示格式，空格用~表示
          StringBuilder IMEI = new StringBuilder(originIMEI);
          IMEI.insert(2, "~");
          IMEI.insert(9, "~");
          IMEI.insert(16, "~");
          //初始化模板
          File template;
          if (imgReq.getIsRandom() == 0) {
            int randomSeed = new Random().nextInt(9999);
            if (randomSeed % 3 == 0) {
              template = FileLoadUtil.loadBackGround("1.jpg");
            } else if (randomSeed % 5 == 0) {
              template = FileLoadUtil.loadBackGround("2.jpg");
            } else if (randomSeed % 2 == 0) {
              template = FileLoadUtil.loadBackGround("3.jpg");
            } else template = FileLoadUtil.loadBackGround("4.jpg");
          } else {
            template = FileLoadUtil.loadBackGround(imgReq.getTemplateName());
          }
          //初始化画布
          BufferedImage background = resizeImage(750, 1334, ImageIO.read(template));
          Graphics2D g = background.createGraphics();
          g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
          g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          g.setColor(new Color(0x909090));
          //定义横坐标初值
          int X = 365;
          //渲染的字体切换器，1和~使用Avenir字体，其它使用SF Mono字体
          for (int j = 0; j < IMEI.length(); j++) {
            char toDraw = IMEI.charAt(j);
            switch (toDraw) {
              case '1':
                g.setFont(avenir);
                X += 20;
                g.drawString(String.valueOf(toDraw), X, 707);
                break;
              case '~':
                g.setFont(avenir);
                X += 10;
                g.drawString(" ", X, 707);
                break;
              default:
                g.setFont(mono);
                X += 20;
                g.drawString(String.valueOf(toDraw), X, 707);
                break;
            }
          }
          g.dispose();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(background, "jpg", baos);
          byte[] bytes = baos.toByteArray();//转换成字节
          Base64.Encoder encoder = Base64.getEncoder();
          String b64 = encoder.encodeToString(bytes).trim();
          b64 = b64.replaceAll("\n", "").replaceAll("\r", "");
          b64 = "data:image/jpeg;base64," + b64;
          imgList.add(new GenImg(IMEI.toString().replaceAll("~", ""), b64));
        }
      }
      return new ImgResp(imgList);
    } catch (Exception e) {
      e.printStackTrace();
      return new FailResp();
    }
  }

  public BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
    BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(
      bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
    return bufferedImage;
  }
}

@Data
class ImgReq {
  public ArrayList<String> IMEIs;
  public int isRandom; //0 随机 1不随机
  public String templateName; //如果不随机，指定模板名
}


